#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <cstdio>
#include <unistd.h>

namespace mythread
{
    
    // 线程要执行的方法
    // typedef void (*func_t)(ThreadDate *td); // 函数指针类型
    using func_t = std::function<void(const std::string&)>;

    class Thread
    {
    public:
        Thread(const std::string &name, func_t func)
            : _name(name), _func(func)
        {
            std::cout << "create " << name << " success!" << std::endl;
        }

        std::string Status()
        {
            if (_isrunning)
                return "running";
            else
                return "sleep";
        }

        std::string Name()
        {
            return _name;
        }

        void Excute()
        {
            std::cout << _name << " is running!" << std::endl;
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }

        // 把它变成整个类的函数，而不是成员函数,因为有隐含的this指针
        static void *threadRoutine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            self->Excute();
            return nullptr;
        }

        void Start()
        {
            // pthread_t tid;
            int n = ::pthread_create(&_tid, nullptr, threadRoutine, this);
            if (n != 0)
            {
                perror("pthread_create: ");
            }
        }

        void Stop()
        {
            if (_isrunning)
            {
                _isrunning = false;
                pthread_cancel(_tid);
                std::cout << _name << " Stop!" << std::endl;
            }
        }

        void Join()
        {
            pthread_join(_tid, nullptr);
            std::cout << _name << " Joined!" << std::endl;
        }

        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isrunning;
        func_t _func;
    };
}